package com.maniu.maniumediacodec;

import android.content.Context;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import androidx.annotation.NonNull;

import java.io.IOException;

public class LocalSurfaceView  extends SurfaceView implements SurfaceHolder.Callback, Camera.PreviewCallback {
    H264Encode h264Encode;
//    mCamera--》surfaceveiw
    private Camera.Size size;
    private Camera mCamera;
//预览宽高    yuv  有多大   是1  不是2
    byte[] buffer;
    public LocalSurfaceView(Context context) {
        super(context);
    }

    public LocalSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        getHolder().addCallback(this);
    }



    public LocalSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void startPreview() {
        Log.d("LocalSurfaceView", "startPreview");
        try {
            mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
            Camera.Parameters parameters = mCamera.getParameters();
            size = parameters.getPreviewSize();
            mCamera.setPreviewDisplay(getHolder());
            mCamera.setDisplayOrientation(90);
            //YUV data 的大小
            buffer = new byte[size.width * size.height * 3 / 2];
            mCamera.addCallbackBuffer(buffer);
            mCamera.setPreviewCallbackWithBuffer(this);
            mCamera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }

    }


// nv21    古老 android
    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
//        bytes  yuv  图片  手机竖着       画面 竖着 1  横着 2
//            编码  宽 高  交换的
        if (h264Encode == null) {
            this.h264Encode = new H264Encode(size.width, size.height);
            h264Encode.startLive();
        }
//        数据
        h264Encode.encodeFrame(data);
        if(mCamera != null){
            mCamera.addCallbackBuffer(data);
        }
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
        Log.d("LocalSurfaceView", "surfaceCreated");
//        startPreview();
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
        closeCamera();
    }

    //关闭相机
    public void closeCamera() {
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera= null;
        }
    }
}
